<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
// 配置信息
const wifiData = ref({
    name: '',
    password: '',
    ip: '',
    isConnected: false
})
const interValId = ref<any>();
const buttonOk = ref<boolean>(true);

const getWifiStatus = async () => {
    try {
        const response = await axios.get('/api/wifi-state')
        wifiData.value = response.data
        console.log(wifiData.value)
        if(interValId.value){
            clearInterval(interValId.value);
        }
    } catch (error) {
        console.error('请求失败：', error)
    }
}

const checkWifiState = async () => {
    interValId.value = setInterval(() => {
        getWifiStatus();  
    },1000)
}

const setWifiConfig = () => {
    ElMessageBox.confirm(
        '确认修改配置吗?',
        '请注意',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                buttonOk.value = false;
                // 设置wifi信息
                const response = await axios.post('/api/wifi-config', wifiData.value)
                if (response.data) {
                    ElMessage.success('配置修改成功,请关注连接状态!')
                    // 通知重连
                    axios.get('/api/wifi-reconnect')
                    // 检测状态
                    wifiData.value.ip = '--';
                    wifiData.value.isConnected = false;
                    checkWifiState();
                }
                buttonOk.value = true;
            } catch (error) {
                console.error('请求失败：', error)
            }
        })
        .catch(err => console.log(err))
}

// 调用接口，查看当前wifi状态
onMounted(() => {
    getWifiStatus();
})


</script>

<template>
    <el-form :model="wifiData" label-width="200px" style="width: 600px">
        <el-form-item label="当前连接状态: ">
            <span v-if="wifiData.isConnected" style="font-size: 30px; color: #67C23A;">已连接</span>
            <span v-else style="font-size: 30px; color: #F56C6C;">未连接</span>
        </el-form-item>
        <el-form-item label="当前IP: ">
            <span v-if="wifiData.isConnected">{{ wifiData.ip }}</span>
            <span v-else>--</span>
        </el-form-item>
        <el-form-item label="WIFI名称: ">
            <el-input v-model="wifiData.name" />
        </el-form-item>
        <el-form-item label="WIFI密码: ">
            <el-input v-model="wifiData.password" />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" :disabled="!buttonOk" @click="setWifiConfig">修改配置</el-button>
        </el-form-item>
    </el-form>
</template>

<style></style>
